import React, { useState, useRef, useEffect } from 'react';
import { Progress, Button, message, Spin } from 'antd';
import axios from 'axios';

// 查询文件上传任务的进度，每 5 秒轮询一次，显示进度条和状态消息。
const UploadProgressPolling = () => {
  const [isPolling, setIsPolling] = useState(false);
  const [progress, setProgress] = useState(0);
  const [status, setStatus] = useState('等待上传');
  const timerRef = useRef(null);
  // const TASK_ID = 'upload-task-456'; // 假设任务ID已通过上传接口获取
  const POLLING_INTERVAL = 5000; // 5秒

  // 获取任务进度
  const fetchProgress = async () => {
    try {
      const response = await axios.get(`https://api.virapi.com/little7plum585/usual-mock-data/progress`);
      const { progress: p, status: s } = response.data.data;
      setProgress(p);
      setStatus(s);
      
      if (p >= 100) {
        stopPolling(); // 完成后停止轮询
        message.success('文件上传完成');
      }
    } catch (error) {
      message.error('获取进度失败');
      stopPolling();
    }
  };

  // 启动轮询
  const startPolling = () => {
    setIsPolling(true);
    fetchProgress();
    timerRef.current = setInterval(fetchProgress, POLLING_INTERVAL);
  };

  // 停止轮询
  const stopPolling = () => {
    setIsPolling(false);
    clearInterval(timerRef.current);
  };

  // 组件卸载清理
  useEffect(() => stopPolling, []);

  return (
    <div style={{ padding: 20 }}>
      <h2>文件上传进度</h2>
      {!isPolling && (
        <Button type="primary" onClick={startPolling}>
          开始查询进度
        </Button>
      )}
      {isPolling && (
        <Spin spinning={!progress} style={{ marginLeft: 16 }}>
          轮询中（每5秒更新）
        </Spin>
      )}

      <Progress
        percent={progress}
        status={status === '完成' ? 'success' : status === '失败' ? 'error' : 'active'}
        showInfo={false}
        style={{ marginTop: 24, width: 400 }}
      />
      <div style={{ marginTop: 8 }}>
        {status === '进行中' && <span>当前进度：{progress}%</span>}
        {status === '完成' && <span>任务已完成</span>}
        {status === '失败' && <span style={{ color: '#ff4d4f' }}>任务失败，请重试</span>}
      </div>
    </div>
  );
};

export default UploadProgressPolling;